package online.shenme.day15.tcp;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Client {
    public static void main(String[] args) throws IOException {
//        method1();
        method2();
    }

    //客户端输出字符流
    private static void method1() throws IOException {
        Scanner sc = new Scanner(System.in);
        Socket socket = new Socket("Johnzz", 10000);
        while (true) {
            System.out.println("请输入发送内容");
            String line = sc.nextLine();
            socket.getOutputStream().write(line.getBytes(StandardCharsets.UTF_8));
        }
    }

    //客户端输出文件IO流
    private static void method2() throws IOException {
        File file = new File("X:/OneDrive - stu.cdutcm.edu.cn/06技术传播/行业研究/IT/Java/项目/test");
        ThreadPoolExecutor pool=new ThreadPoolExecutor(
                3,10,60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(50),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        findFile(file,pool);
    }
    private static void findFile(File file,ThreadPoolExecutor pool) throws IOException {
        for (File listFile : file.listFiles()) {
            if (listFile.isFile()) {
                String suf = listFile.getName().substring(listFile.getName().lastIndexOf(".") + 1);
                System.out.println(listFile);
                pool.submit(()-> {
                    try {
                        upServer(listFile, suf);
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            } else findFile(listFile,pool);
        }
    }

    private static void upServer(File file, String suf) throws IOException, InterruptedException {

        DatagramSocket send = new DatagramSocket();
        byte[] bytes = suf.getBytes(StandardCharsets.UTF_8);
        send.send(new DatagramPacket(bytes, bytes.length,InetAddress.getByName("Johnzz"),8868));

        Socket socket = new Socket("Johnzz", 10000);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        int b;
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
        bos.flush();
        socket.shutdownOutput();
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String s;
        while ((s = br.readLine()) != null) {
            System.out.println(s);
        }
        socket.close();
        bis.close();
        bos.close();
    }


}

